﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Utils.Common
{
   public static class MapHelper 
    {

        public static  T MapTo<T>( object obj) where T : new()
        {
          
            try
            {
                T t = new T();
 
                PropertyInfo[] propertys = obj.GetType().GetProperties();
                foreach (PropertyInfo property in propertys)
                {
                    System.Reflection.PropertyInfo tpropertyInfo = t.GetType().GetProperty(property.Name);//获取指定名称的属性
                    if (tpropertyInfo != null)
                    {
                        SetValue(t, property.Name, GetValue(obj, property.Name));
                    }
                }

                return t;
            }
            catch {
                return default(T);
            }
 
        }



        private static object GetValue(object obj, string propertyName)
        {
            Type type = obj.GetType(); //获取类型
            System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName); //获取指定名称的属性
            if (propertyInfo != null)
                return propertyInfo.GetValue(obj, null); //获取属性

            return null;
        }

        private static bool SetValue(object obj, string propertyName, object value)
        {
            try
            {
                Type type = obj.GetType(); //获取类型
                System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName); //获取指定名称的属性

                propertyInfo.SetValue(obj, value, null); //给对应属性赋值

                return true;
            }
            catch
            {

                return false;
            }
        }

    }
}
